package com.chuxing.security.interceptor;

import com.chuxing.utils.RedisCache;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.concurrent.TimeUnit;

/**
 * @author LiuQi
 * @create 2024-12-25-17:15
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class IpLimuitInterceptor implements HandlerInterceptor {

    private final RedisCache redisCache;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //获取请求ip地址
        String ip = request.getRemoteAddr();
        //处理本地地址情况
        if (ip.equals("0:0:0:0:0:0:0:1")) {
            ip = "127.0.0.1";
        }
        //在redis中查询是否存在该ip
        Long count = redisCache.getCacheObject("IpLimit" + ip);
        //如果ip不存在，则初始化计数
        if (count == null) {
            count= 1L;
            //设置ip计数到redis，有效期1秒
            redisCache.setCacheObject("IpLimit" + ip, count, 1, TimeUnit.SECONDS);
        } else {
            //如果ip存在，更新redis中的计数
            redisCache.setCacheObject("IpLimit" + ip, count + 1, 1, TimeUnit.SECONDS);
            //判断请求次数是否超过限制
            if (count > 50) {
                response.sendError(429, "请求次数超过限制");
                return false;
            }
        }
        //调用父类的preHandle方法
        return HandlerInterceptor.super.preHandle(request, response, handler);
    }
}
